package com.mmlc.inter;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.androidnetframe.utils.LogUtils;
import com.mmlc.meimei.lichengkongjian.MainActivity;
import com.mmlc.meimei.lichengkongjian.classify.FastGoodsDetailActivity;
import com.mmlc.meimei.lichengkongjian.classify.ProductInfoActivity;
import com.mmlc.meimei.lichengkongjian.home.WebViewActivity;
import com.mmlc.meimei.lichengkongjian.mine.ActivityOrderDetail;
import com.mmlc.utils.SPUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Iterator;

import cn.jpush.android.api.JPushInterface;

import static cn.jpush.android.api.JPushInterface.getRegistrationID;

/**
 * Created by Administrator on 2016/12/9.
 */

/*
{"n_builder_id":0,
        "ad_id":"1581061515",
        "n_only":1,
        "m_content":{"n_extras":{"page":{"url":"http://act.lolever.com/20161208/","page_name":"h5","goods_id":512,"title":"电饭锅"}},"n_content":"电饭锅","n_flag":1,"ad_t":0},"show_type":4}
*/

public class MyReceiver extends BroadcastReceiver {
    private static final String TAG = "JPush";


    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        String type = getType(context, bundle);
        String reg = getRegistrationID(context);
        LogUtils.e("极光","[MyReceiver] 接收Registration Id : " + reg);
        LogUtils.e(TAG, "[PushReceiver] onReceive - " + intent.getAction() + ", extras: "+ getType(context,bundle));
        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
            String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
            Log.d(TAG, "[MyReceiver] 接收Registration Id : " + regId);
            //send the Registration Id to your server...
            LogUtils.e("极光","[MyReceiver] 接收Registration Id : " + regId);

        } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
            Log.d(TAG, "[MyReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
            LogUtils.e("极光","[MyReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));

        } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
            //TODO SHIYIJIAN
            Log.d(TAG, "[MyReceiver] 接收到推送下来的通知");
            int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
            Log.d(TAG, "[MyReceiver] 接收到推送下来的通知的ID: " + notifactionId);
            LogUtils.e("极光","[MyReceiver] 接收到推送下来的通知");
            LogUtils.e("极光","[MyReceiver] 接收到推送下来的通知的ID: " + notifactionId);
            Log.d(TAG, "[MyReceiver] 用户点击打开了通知");
            //打开自定义的Activity
            String extra = bundle.getString("cn.jpush.android.EXTRA");
            try {
                if(TextUtils.isEmpty(extra)){
                    return;
                }
                JSONObject object = new JSONObject(extra);
                JSONObject jsonObject = object.optJSONObject("page");
                if(null == jsonObject){
                    return;
                }
                String page_name = jsonObject.optString("page_name");
                if(page_name.equals("itry_room")){
                    String result=bundle.getString("cn.jpush.android.ALERT");
                    String ti=bundle.getString("cn.jpush.android.NOTIFICATION_CONTENT_TITLE");
                    Intent shiyi=new Intent();
                    shiyi.setAction("com.shiyijian.notify");
                    shiyi.putExtra("msg",result);
                    shiyi.putExtra("title",ti);
                    context.sendBroadcast(shiyi);
                    SPUtils.put(context,"notify_shiyi",false);
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

        } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
            Log.d(TAG, "[MyReceiver] 用户点击打开了通知");
            //打开自定义的Activity
            String extra = bundle.getString("cn.jpush.android.EXTRA");
            try {
                if(TextUtils.isEmpty(extra)){
                    return;
                }
                JSONObject object = new JSONObject(extra);
                JSONObject jsonObject = object.optJSONObject("page");
                if(null == jsonObject){
                    return;
                }
                String page_name = jsonObject.optString("page_name");
                String title = jsonObject.optString("title");
                if(TextUtils.isEmpty(page_name)){
                    //应用在后台
                    Intent i = new Intent(context, MainActivity.class);
                    i.putExtras(bundle);
                    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    context.startActivity(i);

                }else if(page_name.equals("h5")){
                    Intent i = new Intent(context, WebViewActivity.class);
                    String url = jsonObject.optString("url");
                    i.putExtra("title",title).putExtra("url",url);
                    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
                    context.startActivity(i);

                }else if(page_name.equals("goods_detail")){
                    Intent i = new Intent(context, ProductInfoActivity.class);
                    String goods_id = jsonObject.optString("goods_id");
                    i.putExtra("goods_id",goods_id);
                    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
                    context.startActivity(i);

                }else if(page_name.equals("goods_detail_zg")){
                    Intent i = new Intent(context, FastGoodsDetailActivity.class);
                    String goods_id = jsonObject.optString("goods_id");
                    i.putExtra("id",goods_id);
                    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
                    context.startActivity(i);
                }else if(page_name.equals("order_detail")){
                    Intent i = new Intent(context, ActivityOrderDetail.class);
                    String order_id = jsonObject.optString("order_id");
                    i.putExtra("orderId",order_id);
                    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
                    context.startActivity(i);
                }else if(page_name.equals("itry_room")){
                    boolean notify= (boolean) SPUtils.get(context,"notify_shiyi",false);
                    Intent intent2=new Intent(context,MainActivity.class);
                    if(!notify){
                        intent2.putExtra("flag",4);
                        intent2.putExtra("isNotify",true);
                        String result=bundle.getString("cn.jpush.android.ALERT");
                        String ti=bundle.getString("cn.jpush.android.NOTIFICATION_CONTENT_TITLE");
                        intent2.putExtra("msg",result);
                        intent2.putExtra("title",ti);
                    }

                    intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
                    context.startActivity(intent2);
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
//            Intent i = new Intent(context, TestActivity.class);
//            i.putExtras(bundle);
//            //i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
//            context.startActivity(i);

        } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
            Log.d(TAG, "[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
            //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity， 打开一个网页等..

            LogUtils.e("极光", "[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));

        } else if(JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
            boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
            Log.w(TAG, "[MyReceiver]" + intent.getAction() +" connected state change to "+connected);
            LogUtils.e("极光", "[MyReceiver]" + intent.getAction() +" connected state change to "+connected);
        } else {
            Log.d("极光", "[MyReceiver] Unhandled intent - " + intent.getAction());
            LogUtils.e("极光", "[MyReceiver] Unhandled intent - " + intent.getAction());
        }
    }

    public static String getResId(Context context){
        return getRegistrationID(context);
    }
    private String getType(Context context, Bundle bundle) {

        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
            } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
            } else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
                if (bundle.getString(JPushInterface.EXTRA_EXTRA).isEmpty()) {
                    Log.i(TAG, "This message has no Extra data");
                    continue;
                }

                try {
                    JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                    Iterator<String> it = json.keys();

                    while (it.hasNext()) {
                        String myKey = it.next().toString();
                        sb.append("\nkey==>:" + key + ", value: [" +
                                myKey + " - " + json.optString(myKey) + "]");

                        if ("type".equals(myKey)) {
                            return json.optString(myKey);
                        }
                    }
                } catch (JSONException e) {
                    Log.e(TAG, "Get message extra JSON error!");
                }

            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
            }


        }

        return sb.toString();
    }


}
